package com.ygqh.baby.controller.mobile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.payment.PayRequest;
import com.foxinmy.weixin4j.type.TradeType;
import com.ygqh.baby.ao.AppType;
import com.ygqh.baby.ao.CodeType;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.PayType;
import com.ygqh.baby.exception.YgException;
import com.ygqh.baby.model.BaseSkuInfo;
import com.ygqh.baby.po.KsdOrder;
import com.ygqh.baby.service.KsdOrderService;
import com.ygqh.baby.service.WxMpAuthorityService;
import com.ygqh.baby.service.YgFrameCodeService;
import com.ygqh.baby.service.YgOrderPaymentService;
import com.ygqh.baby.service.impl.DocumentConstant;
import com.ygqh.baby.service.wechat.YgWeChatService;
import com.ygqh.baby.service.wechat.protocol.UnifiedOrderReqData;
import com.ygqh.baby.utils.WebUtils;

/**
 * 购物车相关
 * 
 * @author guohao
 *
 */
@Controller
@RequestMapping("/mobile/popupstore")
public class YgPopUpStoreController {
	protected final Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private DocumentConstant documentConstant;
	@Autowired
	private KsdOrderService ksdOrderService;
	@Autowired
	private YgWeChatService ygWeChatService;
	@Autowired
	private YgOrderPaymentService ygOrderPaymentService;
	@Autowired
	private YgFrameCodeService ygFrameCodeService;
	@Autowired
	private WxMpAuthorityService wxMpAuthorityService;

	@Value("${micro.msg.appId}")
	private String appid;
	@Value("${wechat.pay.mchid}")
	private String mchid;
	@Value("${micro.msg.secret}")
	private String appsecret;
	@Value("${wechat.pay.ksd.notify_url}")
	private String notify_url;

	final static String KSD_KEY = "KSD-";

	/**
	 * 创建快闪店订单
	 * 
	 * @param skuId
	 * @param quantity
	 * @param callback
	 * @return
	 * @throws WeixinException
	 */
	@RequestMapping(value = "commitOrder", method = RequestMethod.GET)
	@ResponseBody
	public JSONPObject commitOrderPt(String skuInfos, PayType payType, String callback) throws YgException, WeixinException {
		List<BaseSkuInfo> skuList = JSON.parseObject(skuInfos, new TypeReference<List<BaseSkuInfo>>() {
		});

		// 订单保存成功
		Message msg = ksdOrderService.commitOrder(skuList);
		if (msg.getType().equals(Message.Type.success)) {
			KsdOrder ksdOrder = (KsdOrder) msg.getExtra();
			String qrCodeUrl = wxMpAuthorityService.findQrCodeUrl(KSD_KEY + ksdOrder.getOrderId() + "-" + ksdOrder.getTotalPrice());
			return new JSONPObject(callback, Message.success(qrCodeUrl));
		}
		return new JSONPObject(callback, msg);
	}

	@RequestMapping(value = "UnifiedOrderJSAPI")
	@ResponseBody
	public JSONPObject UnifiedOrderJSAPI(String openId, BigDecimal totalPrice, Long orderId, String callback, HttpServletRequest request) {

		Message msg = null;
		String ipAddress = WebUtils.getIpAddr(request);
		System.out.println("客户端ip：" + ipAddress);
		String[] split = ipAddress.split(",");
		ipAddress = split[0];
		System.out.println("客户端ip：" + ipAddress);
		PayRequest payRequest = null;
		try {
			// 生成支付流水
			Long paymentCode = ygFrameCodeService.getFrameCode(CodeType.OrderPM, new Date());

			UnifiedOrderReqData reqData = new UnifiedOrderReqData.UnifiedOrderReqDataBuilder(appid, mchid, "壹果订单", paymentCode.toString(),
					totalPrice.multiply(new BigDecimal(100)).intValue(), ipAddress, notify_url, TradeType.JSAPI.name()).setOpenid(openId).build();
			msg = ygWeChatService.UnifiedOrderJSAPI(reqData);
			if (msg.getType().equals(Message.Type.error)) {
				return new JSONPObject(callback, Message.error(documentConstant.MESSAGE_ERROR, msg));
			}
			payRequest = (PayRequest) msg.getExtra();
			payRequest.setPartnerId(paymentCode.toString());
			ygOrderPaymentService.addPaymentRecord(orderId.toString(), totalPrice, paymentCode.toString(), PayType.WeChat, AppType.WeChat);
		} catch (Exception e) {
			logger.error("JSAPI;发起微信支付失败" + e.getMessage());
			e.printStackTrace();
			return new JSONPObject(callback, Message.error(documentConstant.MESSAGE_ERROR, null));
		}
		return new JSONPObject(callback, Message.success(payRequest));
	}

	/**
	 * 微信统一下单回调
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "unifiedOrderCallBack")
	public void unifiedOrderCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		ServletInputStream in = request.getInputStream();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = in.read(buffer)) != -1) {
			out.write(buffer, 0, len);
		}
		String result = new String(out.toByteArray(), "UTF-8");

		String res = ygWeChatService.KSDUnifiedOrderCallBack(result);

		logger.debug("\n微信支付回调返回结果：\n" + res);
		out.close();
		in.close();
		response.getWriter().print(res);
	}

	@RequestMapping(value = "getOrderDetail")
	@ResponseBody
	public JSONPObject getOrderDetail(Long orderId, String callback, HttpServletRequest request) {
		List<Map<String, Object>> list = ksdOrderService.findOrderDetail(orderId);
		return new JSONPObject(callback, Message.success(list));
	}

}
